<?php

class Converter {

	protected $sourcefile;

	public function setSourceFile($file)
	{
		$this->sourcefile=$file;
	}

	public function download()
	{
		$staticRow=$this->additionalRow();

		$sourceFile=Config::get("appconfig.uploadFolder").$this->sourcefile;

		$result = Excel::load($sourceFile)->get();

		$outputArray=$result->map(function($item){
			return $this->rowFormat($item);
		})->toArray();


		$list=[];
		foreach($outputArray as $item)	{
			array_push($list, $item);
			array_push($list, $staticRow);
		}
		$outputArray=$list;

		$excelOutput=	Excel::create('eParcel', function($excel) use($outputArray,$staticRow){
			$excel->sheet('Sheetname', function($sheet) use($outputArray,$staticRow){
				$sheet->setColumnFormat(array(
				    'P' => '@'
				));
				$sheet->fromArray($outputArray);
			});
		});

		File::delete($sourceFile);
		$excelOutput->export('csv');
	}

	private function additionalRow()
	{
		return explode(",", "A,0.5,20,10,10,1,,,N,0");
	}

	private function rowFormat($item)
	{
			return [
			"C",  //a
			null, 
			null, 
			"S1", //d
			null,
			$item->buyer_fullname,//f
			null,
			$item->buyer_address_1,//h
			$item->buyer_address_2!==null?$item->buyer_address_2:"",//i
			null,
			null,
			$item->buyer_city,//l
			$this->stateMap($item->buyer_state),//m
			$item->buyer_postcode,//n
			"AU",//$item->buyer_country,//o
			$this->phoneFormat($this->fixPhone($item->buyer_phone_number)),//p
			null,
			null,
			null,
			"Y",
			null,
			null,
			null,
			null,
			null,
			null,
			null,
			"Y",
			null,
			null,
			null,
			null,
			null,
			null,
			null,
			null,
			null,
			null,
			null,
			null,
			null,
			null,
			null,
			null,
			null,
			null,
			null,
			null,
			null,
			null,
			$item->buyer_email,//p
			"TRACKADV"
			];
	}

	private function stateMap($fullStateName)
	{
		$fullStateName= trim($fullStateName);
		$fullStateName= strtolower($fullStateName);

		$map=[
			"queensland"=>"QLD",
			"qld"=>"QLD",
			"new south wales"=>"NSW", 
			"nsw"=>"NSW", 
			"victoria" => "VIC", 
			"vic" => "VIC", 
			"south australia" => "SA", 
			"sa" => "SA", 
			"western australia" => "WA", 
			"wa" => "WA", 
			"northern territory" => "NT", 
			"nt" => "NT", 
			"tasmania" => "TAS",
			"tas" => "TAS",
			"australian capital territory" => "ACT",
			"act" => "ACT"
		];

		if($map[$fullStateName]!== null){
			return $map[$fullStateName];

		}else {
			return $fullStateName;
		}
	}

	private function fixPhone($phone)
	{
		if(starts_with($phone, "61")){
		 	return $phone;
		 } else {
			return "610".$phone;
		 }
	}

	private function phoneFormat($phone)
	{

		if (preg_match( '/^(61)(.*)/', $phone,  $matches )) {
			$nationCode = $matches[1] ;
			$phoneNum=$matches[2];
		}

		if (preg_match( '/^(\d{4})(\d{3})(\d+)/', $phoneNum,  $phoneMatches )) {
			$result=$nationCode." ". $phoneMatches[1]." ". $phoneMatches[2]." ". $phoneMatches[3];
		}



		if(isset($result)){
			return $result;
		} else {
			return $phone;
		}
		

	}
}